<template>
  <div class="employees-container">
    <!-- {{ $store.getters.roles.points }} -->
    <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userID" />
    <div class="app-container">
      <el-dialog width="300px" title="二维码" :visible="showCodeDialog" @close="closeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push(`/import?type=user`)">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img v-imgerror="defaultImage" class="staff" :src="row.staffPhoto || defaultImage" alt="" @click="clickShowCodeDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column :formatter="formatterFn" label="聘用形式" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              <!-- {{ formatDate(row.timeOfEntry,'/') }} -->
              {{ row.timeOfEntry | formatDate('/') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <!-- <el-table-column label="操作" sortable="" fixed="right" width="280"> -->
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                v-if="checkPermissions('aa')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
          <!-- </el-table-column> -->
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <!--
            total 总条数
            current-page 当前页 并且显示高亮
            page-size 每页展示的条数
            layout 展示布局， 这里不是完整的功能 就展示 左箭头（上一页） 页码 右箭头（下一页）
            current-change 切换页码
           -->
          <el-pagination

            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" @add-employee="getEmployeeList" />
    <!-- 完整写法<add-employee :show-dialog="showDialog" @update:showDialog="showDialog = $event" /> -->
  </div>
</template>
<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import { formatDate } from '@/filters/index'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
// import { formatDate } from '@/filters/index'
import hello from '@/Mixins/hello'
import checkedPermission from '@/Mixins/checkedPermission'
console.log(EmployeeEnum.hireType)
export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  mixins: [hello, checkedPermission],
  data() {
    return {
      userID: '',
      showRoleDialog: false,
      showCodeDialog: false,
      defaultImage: 'https://img0.baidu.com/it/u=3245291370,1990477496&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667',
      showDialog: false,
      list: [],
      page: 1, // 当前页
      pageSize: 10, // 每页条数
      total: 0, // 总数
      loading: false,
      hh: '嘻嘻嘻'
    }
  },
  created() {
    this.getEmployeeList()
    console.log(this.hh)
    this.sayHi()
  },
  methods: {
    sayHi() {
      console.log('hi')
    },
    // checkPermissions(key) {
    //   return this.$store.getters.roles?.points?.includes?.(key)
    // },
    editRole(id) {
      this.showRoleDialog = true
      this.userID = id
    },
    clickShowCodeDialog(url) {
      if (!url) return
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.showCodeDialog = false
    },
    async handleDownload() {
      // this.downloadLoading = true
      // 由于js-xlsx体积还是很大的，导出功能也不是一个非常常用的功能，所以使用的时候建议使用懒加载
      // 获取列表
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      // console.log(rows)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const arrData = this.formatJson(rows, headersArr, headersRelations)
      console.log(arrData)
      import('@/vendor/Export2Excel').then(excel => {
        // const data = [
        //   [1, 'zs', 18],
        //   [2, '大聪明', 16]
        // ]
        excel.export_json_to_excel({
          header: headersArr,
          data: arrData,
          multiHeader,
          merges
          // filename: this.filename,
          // autoWidth: this.autoWidth,
          // bookType: this.bookType
        })
        // this.downloadLoading = false
      })
    },
    formatJson(rows, headersArr, headersRelations) {
      // console.log('11', rows)
      const result = []
      // 拼接二维数组
      rows.forEach(row => {
        const arr = []
        headersArr.forEach(header => {
          // console.log('66', header)
          const englishKey = headersRelations[header]
          let value = row[englishKey]
          // 修改导出日期格式
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = formatDate(value, '/')
          }
          // 处理聘用格式
          // 111
          if (englishKey === 'formOfEmployment') {
            value = EmployeeEnum.hireType.find(item => item.id === +value)?.value || '未知'
            // console.log('990', value)
          }
          arr.push(value)
        })
        result.push(arr)
      })
      return result
    },
    delEmployee(id) {
      this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
        console.log('取消')
      })
    },
    // formatDate,
    // 用来格式化内容
    formatterFn(row, column, cellValue, index) {
      // console.log({ row, column, cellValue, index })
      // return cellValue
      // 可选链运算符（?.）
      return EmployeeEnum.hireType.find(item => item.id === +cellValue)?.value || '未知'
      // const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      // return obj ? obj.value : '未知'
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    async getEmployeeList() {
      this.loading = true
      const { data } = await reqGetEmployeeList(this.page, this.pageSize)
      const { total, rows } = data
      this.total = total
      this.list = rows
      this.loading = false
    }
  }
}
</script>
<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
